ASP.NET+MVC+使用+Log4net+记录日志笔记 您所在的位置:网站首页 net core日志记录 ASP.NET+MVC+使用+Log4net+记录日志笔记

ASP.NET+MVC+使用+Log4net+记录日志笔记

2023-03-27 21:42| 来源: 网络整理| 查看: 265

前言:

记录系统中的日志,是一个好的项目产品必备的一个环节。每一个产品最终的目的都是要交予客户使用,因为程序员代码的开发水平参差不齐,Bug就成为了项目运维成本最大的因素之一。如何降低项目运维的成本呢,最重要的是要缩短开发人员在系统运维排查问题的时间成本。如果你的系统中很好的集成了日志框架。那么你可以更快更高效的定位问题、解决问题。从而降低系统运维的时间成本。今天小编给大家介绍Log4net日志框架如何在项目中 使用,希望能对大家有所帮助。

Log4net 介绍

1、Log4net 是什么?

Log4net 是 Apache 旗下一个开源的日志框架的项目,它是Log4j 的一个复制版。Log4net中定义了多种日志信息输出模式。它可以根据需要将日志输出到控制台、文本文件、windows 日志事件查看器中、括数据库,邮件发送,以便我们可以根据日志快速定位线上系统的问题。

2、Log4net 日志等级

从高到底分别为:OFF > FATAL > ERROR > WARN > INFO > DEBUG  > ALL

二、ASP.NET MVC 使用 Log4net 示例

2.1 如何安装 Log4net Log4net

使用Nuget 安装 Log4net(工具-NuGet包管理器-程序包管理器控制台(N))

                       

使用管理NuGet程序包功能找到Log4net进行安装。

                         

2.2 创建 log4net.config 配置文件 ,并且将该文件的属性“复制到输出目录”修改为 “始终复制。

                       

log4net.config内容如下:

2.3 新建LogHelper.cs通用日志类

                       

代码如下:

public class LogHelper { private ILog _log4Net = null; private const string DEFAULT_LOGGER_NAME = "Logger"; /// /// Prevents a default instance of the class from being created. /// /// The log4net instance to be used. private LogHelper(ILog log4NetInstance) { _log4Net = log4NetInstance; } /// /// Gets a logger with the specified configuration name. /// /// Name of the logger in the configuration. /// The logger obtained. /// Thrown when no logger with the specified configuration name was found. public static LogHelper GetLogger(string configName) { var logger = LogManager.GetLogger(configName); if (logger == null) { throw new ArgumentException(string.Format("No logger configuration named '{0}' was found in the configuration.", configName), "configName"); } return new LogHelper(logger); } /// /// Gets the default. /// public static LogHelper Default { get { return GetLogger(DEFAULT_LOGGER_NAME); } } /// /// Writes an information level logging message. /// /// The message to be written. public void WriteInfo(object message) { _log4Net.Info(message); } /// /// Writes a warning level logging message. /// /// The message to be written. public void WriteWarning(object message) { _log4Net.Warn(message); } /// /// Writes a warning level logging message. /// /// The message to be written. /// The exception. public void WriteWarning(object message, System.Exception exception) { _log4Net.Warn(message, exception); } /// /// Writes the error. /// /// The message to be written. public void WriteError(object message) { _log4Net.Error(message); } /// /// Writes the error level logging message.. /// /// The message to be written. /// The exception. public void WriteError(object message, System.Exception exception) { _log4Net.Error(message, exception); } /// /// Writes the fatal error level logging message.. /// /// The message to be written. public void WriteFatal(object message) { _log4Net.Fatal(message); } /// /// Writes the fatal error level logging message.. /// /// The message to be written. /// The exception. public void WriteFatal(object message, System.Exception exception) { _log4Net.Fatal(message, exception); } public void DeleteLog() { string logDirPath = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "Log"); if (!Directory.Exists(logDirPath)) return; int days = 30; foreach (string filePath in Directory.GetFiles(logDirPath)) { DateTime dt; DateTime.TryParse(Path.GetFileNameWithoutExtension(filePath).Replace(@"Log\", "").Replace(".", "-"), out dt); if (dt.AddDays(days).CompareTo(DateTime.Now) < 0) { File.Delete(filePath); } } } }

2.4 AssemblyInfo.cs 文件配置log4net.config

特别注意:针对为web项目要加载web项目对应的AssemblyInfo.cs文件中去,这一点很关键要不然就不能输出日志文件

[assembly: log4net.Config.XmlConfigurator(Watch = true, ConfigFileExtension = "config", ConfigFile = @"Configs\log4net.config")]

                       

2.5 自定义日志异常处理文件:MyExceptionFileAttribute.cs

用来处理异常记录日志文件,然后可以指定错误的跳转页面。

public override void OnException(ExceptionContext filterContext) { base.OnException(filterContext); if (!string.IsNullOrWhiteSpace(filterContext.Exception.StackTrace)) { LogHelper.Default.WriteError(filterContext.Exception.StackTrace); } //页面跳转到错误页面 filterContext.HttpContext.Response.Redirect("/Error"); }

2.6 Global.asax新增Log4Net的配置信息

Application_Start.cs 方法加入下面两行代码:

// 注册log4net log4net.Config.XmlConfigurator.Configure(); // 注册异常日志文件 GlobalFilters.Filters.Add(new MyExceptionFileAttribute());

测试用法

LoginController.cs 代码加一个异常

public ActionResult Index() { int a = 0; int b = 6 / a; return View(); }

效果展示:

                       

结语

本文主要简单介绍ASP.NET MVC 使用 Log4net 的过程。具体的一些用法大家也可以互相交流,比如:如何错误日志如何发邮件、数据库的方式存储、日志文件异步存储等等。后续小编会继续更新相关内容和大家一起学习交流。

IT技术分享社区

个人博客网站:https://programmerblog.xyz

文章推荐程序员效率:画流程图常用的工具程序员效率:整理常用的在线笔记软件远程办公:常用的远程协助软件,你都知道吗?51单片机程序下载、ISP及串口基础知识硬件:断路器、接触器、继电器基础知识



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有